package com.sjyl.kaoshitong.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.CatalogItem;
import com.sjyl.kaoshitong.beans.DepartmentInfo;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.FontIconUtil;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.sjyl.kaoshitong.witget.FilterBranchSelectorDialog;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tr.xip.errorview.ErrorView;

/**
 * Created by ChangerLow on 15/6/25.
 * Email: changerlow@qq.com
 */
public class FilterMainFragment extends Fragment implements View.OnClickListener, FilterBranchSelectorDialog.BranchSelectCallback {
    private static final String TAG = "FilterMainFragment";
    private LinearLayout progressLayout;
    private ErrorView errorView;
    private LinearLayout mainContent;
    private TextView departTV;
    private TextView branchTV;
    private Button submitBtn;
    private Toast mToast;
    private OkHttpClient okHttpClient;
    private ProgressDialog progressDialog;

    private Gson gson = new Gson();
   // private SharedPreferences preferences;
   // private SharedPreferences.Editor editor;
    private List<DepartmentInfo> departList;
    private String[] departNameList;
    private String selectedDepartID = "1";
    private Map<String, CatalogItem> catalogItemMap;
    private String dropDownIcon = FontIconUtil.ARROW_DROP_DOWN;

    public static FilterMainFragment newInstance(String arg) {
        FilterMainFragment fragment = new FilterMainFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //  preferences = getActivity().getSharedPreferences("kaoshitong", Context.MODE_PRIVATE);
        // editor = preferences.edit();
        Hawk.init(getActivity());
        catalogItemMap = new HashMap<String, CatalogItem>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_filter_layout, container, false);
        progressLayout = (LinearLayout) view.findViewById(R.id.refresh_layout);
        errorView = (ErrorView) view.findViewById(R.id.error_view);
        mainContent = (LinearLayout) view.findViewById(R.id.main_content);
        departTV = (TextView) view.findViewById(R.id.depart_tv);
        branchTV = (TextView) view.findViewById(R.id.grade_tv);
        submitBtn = (Button) view.findViewById(R.id.submit_btn);
        departTV.setOnClickListener(this);
        branchTV.setOnClickListener(this);
        submitBtn.setOnClickListener(this);
        errorView.setOnRetryListener(new ErrorView.RetryListener() {
            @Override
            public void onRetry() {
                showToast(getActivity().getString(R.string.info_retrying));
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        getDepartList();
                    }
                });
            }
        });
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        showProgress();
        getDepartList();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.depart_tv:
                if (departNameList.length > 0) {
                    new MaterialDialog.Builder(getActivity())
                            .title(R.string.filter_label_title_department)
                            .items(departNameList)
                            .itemsCallback(new MaterialDialog.ListCallback() {
                                @Override
                                public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                    //showToast(which + ": " + text);
                                    departTV.setText(text + dropDownIcon);
                                    selectedDepartID = departList.get(which).getId();
                                    Hawk.put(PreferencesKeyUtil.KEY_DEPART_ID, selectedDepartID);
                                    Logger.d(TAG, "selected department id is " + selectedDepartID + "  departmeng name is " + text);
                                    getBranchInfo();
                                }
                            })
                            .show();
                } else {
                    ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.no_more_date));
                }


                break;
            case R.id.grade_tv:
                FilterBranchSelectorDialog dialog = FilterBranchSelectorDialog.newInstance("");
                dialog.setTargetFragment(this, 1);
                dialog.show(getFragmentManager(), "dialog");
                break;
            case R.id.submit_btn:
                getActivity().finish();
                break;
            default:
                break;
        }

    }

    private void showToast(String message) {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
        mToast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
        mToast.show();
    }

    private void showProgress() {
        progressLayout.setVisibility(View.VISIBLE);
        mainContent.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
    }

    private void showContent() {
        progressLayout.setVisibility(View.GONE);
        mainContent.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }

    private void showErrorview() {
        progressLayout.setVisibility(View.GONE);
        mainContent.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);

    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage(getActivity().getString(R.string.data_loading));
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }


    private void getDepartList() {
        showProgress();
        RequestBody body = new FormEncodingBuilder().add("funName", "getDepartList").build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showErrorview();
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // Logger.json(TAG, response.body().string());
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<DepartmentInfo>>() {
                }.getType();
                final ApiResponse<DepartmentInfo> apiResponse = gson.fromJson(body, type);
                departList = apiResponse.getRecontent().getRelist();
                departNameList = new String[departList.size()];
                for (int i = 0; i < departList.size(); i++) {
                    departNameList[i] = departList.get(i).getDepart_name();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!apiResponse.getRecode().equals("2000")) {
                            showErrorview();
                        } else {
                            Logger.d(TAG, "=========recode:" + " relist size:" + departList.size() + " " + departList.get(0).getDepart_name());
                            if (departList.size() > 0) {
                                DepartmentInfo departInfo = departList.get(0);
                                departTV.setText(departInfo.getDepart_name() + dropDownIcon);
                            } else {
                                selectedDepartID = "1";
                            }
                            showContent();
                        }
                    }
                });

            }
        });
    }


    private void getBranchInfo() {
        showProgressDialog();
        Logger.d(TAG, "get Branch list    department id is " + selectedDepartID);
        RequestBody body = new FormEncodingBuilder().add("funName", "getDataCatalogList").add("departId", selectedDepartID).add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID,"")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.filter_get_branch_error));
                        }
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // Logger.json(TAG, response.body().string());
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<CatalogItem>>() {
                }.getType();
                final ApiResponse<CatalogItem> apiResponse = gson.fromJson(body, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (!apiResponse.getRecode().equals("2000")) {
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.filter_get_branch_error));
                        } else {
                            List<CatalogItem> list = apiResponse.getRecontent().getRelist();
                            Logger.d(TAG, "=========recode:" + " relist size:" + list.size());
                            Hawk.put(PreferencesKeyUtil.KEY_CATALOG_LIST, list);
                            branchTV.setText(list.get(0).getCatalog_name() + dropDownIcon);
                        }
                    }
                });

            }
        });
    }


    private int processCatalogList(List<CatalogItem> list) {
        if (list.size() == 0)
            return 0;
        int maxLevel = 0;
        catalogItemMap.clear();
        Logger.d(TAG, "catalog list size is " + list.size());
        for (int i = 0; i < list.size(); i++) {
            CatalogItem catalogItem = list.get(i);
            int catalog_level = catalogItem.getCatalog_level();
            Logger.d(TAG, "Processing catalog level is " + catalog_level);
            String id = catalogItem.getId();
            if (catalog_level > maxLevel) {
                maxLevel = catalog_level;
            }
            catalogItemMap.put(id, catalogItem);

        }

        return maxLevel;
    }


    @Override
    public void onBranchSelection(List<String> ids) {
        List<String> selectedName = Hawk.get(PreferencesKeyUtil.KEY_FILTER_SELECTED_PATH);
        String branchPathName = TextUtils.join(">", selectedName);
        branchTV.setText(branchPathName + dropDownIcon);
    }
}
